var express = require('express');
var router = express.Router();
const { cateFind, getNextSequenceValue } = require('./funcs')
const Cate = require('../mongoose/models/Cate')

// 分类列表
router.get('/list', async function(req, res, next) {
  cateFind((data)=>{
    res.status(200).send({
      data,
      code: 1,
      msg: '操作成功'
    })
  }, req.query)
});

router.post('/add', async function(req, res, next) {
  const body = req.body

  body.catid = await getNextSequenceValue("food_id")

  body.sort = Number(body.sort)

  new Cate(body).save(function(err, cate) {
    if (err) {
      res.send({
        code: 999,
        msg: err,
      });
    }else if(!cate){
      res.send({
        code: 999,
        msg: '网络错误',
      });
    }else{
      res.send({
        code: 1,
        data: cate,
        msg: '添加成功!'
      })
    }
  })
});

router.post('/del', async function(req, res, next) {

  const { catid } = req.body;

  Cate.deleteOne({catid: Number(catid)}, (err, data) => {
    if (err) {
      res.send({
        code: 999,
        msg: err,
      });
    }
    else if(!data) {
      res.send({
        code: 999,
        msg: "未查找到相关数据!",
      });
    }else{
      res.send({
        code: 1,
        msg: "删除成功!",
        data
      });
    }
  });
});

router.post("/edit", function (req, res, next) {
  let catid = Number(req.body.catid)
  req.body.catid = catid

  Cate.findOneAndUpdate({catid}, {$set: req.body}, function(err, data) {
    if(err) {
      res.send({
        code: 999,
        msg: "数据库发生错误!",
      });
      return
    }
    else if(!data) {
      res.send({
        code: 999,
        msg: "未查找到相关数据!",
      });
      return
    }
    else if(data){
      res.send({
        code: 1,
        msg: "修改成功!",
      });
    }
  })
})


/**
 * 给Cate（Model） 添加一个字段 store: "1"
 */
router.get("/insertoneprop", async function (req, res, next) {
  if (req.query.key !== 'INSERTONEPROPREWCSQWEJGKR123DFG12') {
    res.send({
      code: 500,
      msg: '暂无权限'
    }) 
    return
  }
  Cate.updateMany({}, { store: "1" }, function (err, docs) {
    if (err) {
      res.send({
        code: 500,
        msg: err
      })
    } else {
      res.send({
        code: 1,
        msg: '操作成功！'
      })
    }
  });
});

module.exports = router;